﻿<template>
    <el-input-number v-model="currentValue"
                     :min="min"
                     :max="max"
                     :placeholder="$t(placeholder)"
                     :step="step"
                     :precision="myPrecision"
                     :controls="controls"
                     :controls-position="controlsPosition"
                     :size="size"
                     @change="change"
                     @blur="blur"
                     @focus="focus"></el-input-number>
</template>

<script>
export default {
  name: 'form-input-number',
  data () {
    return {
      currentValue: this.value == '' || this.value == null ? undefined : this.value
    }
  },
  props: {
    value: {
      default () {
        return undefined
      }
    },
    size: {
      type: String,
      default: ''
    },
    placeholder: String,
    min: {
      type: Number,
      default: 0
    },
    max: {
      type: Number,
      default: Infinity
    },
    step: Number,
    precision: Number,
    controls: {
      type: Boolean,
      default: true
    },
    controlsPosition: String
  },
  watch: {
    value (newVal) {
      this.currentValue = newVal
    },
    currentValue (newVal) {
      this.$emit('input', newVal)
    }
  },
  computed: {
    myPrecision () {
      let precision = this.precision

      // 未设置精度，但已设置步长，根据步长自动计算精度
      if (
        Object.prototype.toString.call(this.precision) ==
                    '[object Undefined]' &&
                    Object.prototype.toString.call(this.step) == '[object Number]'
      ) {
        let pointPosition = this.step.toString().indexOf('.')

        if (pointPosition > 0) {
          precision = this.step.toString().length - pointPosition - 1
        }
      }

      return precision
    }
  },
  methods: {
    change (newValue) {
      this.$emit('change', newValue)
    },
    blur (e) {
      this.$emit('blur', e)
    },
    focus (e) {
      this.$emit('focus', e)
    }
  }
}
</script>
